window.onload = function(){
    const videoUrl = 'https://www.pasanhu.cn/Resource/PaseCn/HYHG/Rista/files/1.mp4';
    const chunkSize = 1024 * 1024; // 每个分片的大小，这里设置为1MB
    const start = 0; // 开始位置
    let end = start + chunkSize; // 结束位置
    
    function fetchChunks(url, start, end) {
        const range = `bytes=${start}-${end - 1}`;
        return fetch(url, {
            method: 'GET',
            headers: {
            'Range': range,
            },
        }).then(response => {
            if (response.ok) {
            return response.arrayBuffer();
            }
            throw new Error('Network response was not ok.');
        });
    }
    
    function downloadVideo() {
    const videoFile = []; // 存储所有分片的数组
    let receivedSize = 0; // 已接收的数据大小
    
    function downloadChunk() {
        if (receivedSize >= chunkSize) return; // 所有分片已下载完毕
        fetchChunks(videoUrl, start, end).then(chunk => {
        videoFile.push(chunk);
        receivedSize += chunk.byteLength;
        start = end;
        end = start + chunkSize;
        downloadChunk(); // 递归下载下一个分片
        }).catch(error => {
        console.error('Error fetching chunk:', error);
        });
    }
    
    downloadChunk(); // 开始下载第一个分片
    
    // 当所有分片下载完毕时，合并分片并创建Blob URL
    return new Promise((resolve, reject) => {
        const onLoad = () => {
        const blob = new Blob(videoFile, { type: 'video/mp4' }); // 假设视频格式为mp4
        const blobUrl = URL.createObjectURL(blob);
        resolve(blobUrl);
        };
    
        const onError = (error) => {
        reject(error);
        };
    
        const reader = new FileReader();
        reader.onload = onLoad;
        reader.onerror = onError;
    
        // 当所有分片数据都收集完成后，使用FileReader读取它们
        reader.readAsArrayBuffer(new Blob(videoFile));
    });
    }
    
    // 使用下载函数并处理结果
    downloadVideo().then(blobUrl => {
        // 使用blobUrl创建视频标签并插入文档中
        const videoElement = document.createElement('video');
        videoElement.src = blobUrl;
        videoElement.controls = true;
        document.body.appendChild(videoElement);
        
        // 清理：移除blob URL
        videoElement.addEventListener('loadedmetadata', () => {
            URL.revokeObjectURL(blobUrl);
        });
    }).catch(error => {
        console.error('Error downloading video:', error);
    });
}